package gecko.x;

/**
 * @author 陈永佳 (yoojiachen@gmail.com)
 * @version 0.0.1
 */
public class ByteX {

    private final static char[] hexArray = "0123456789ABCDEF".toCharArray();

    public static String hex(byte[] bytes) {
        final StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            int v = b & 0xFF;
            sb.append(hexArray[v >>> 4]);
            sb.append(hexArray[v & 0x0F]);
            sb.append(' ');
        }
        return sb.toString().trim();
    }

    public static String hex(byte b) {
        return hex(new byte[]{b});
    }

    public static String hex(int value) {
        return hex(toBytes(value, true));
    }

    public static String hex(int value, boolean bigEndian) {
        return hex(toBytes(value, bigEndian));
    }

    public static String hex(short value) {
        return hex(toBytes(value));
    }

    public static byte[] toBytes(int value, boolean bigEndian) {
        // 默认为大字节顺序
        if (bigEndian) {
            return new byte[]{
                    (byte) (value >> 24),
                    (byte) (value >> 16),
                    (byte) (value >> 8),
                    (byte) value,
            };
        } else {
            return new byte[]{
                    (byte) value,
                    (byte) (value >> 8),
                    (byte) (value >> 16),
                    (byte) (value >> 24),
            };
        }
    }

    public static byte[] toBytes(short value) {
        return new byte[]{
                (byte) (value >> 8),
                (byte) value};
    }
}
